package com.ckerchina.admin.ckadmin.utils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;

import com.ckerchina.admin.ckadmin.exception.ErrorCode;
import com.ckerchina.admin.ckadmin.exception.ZhuziException;

public class CommonUtil {

	public static String genRandomNum(int num) {
		Random random = new Random();
		String sRand = "";
		for (int i = 0; i < num; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
		}
		if (sRand.substring(0, 1).equals("0")) {
			sRand = "1" + sRand.substring(1);
		}
		return sRand;
	}

	public static Integer getRandomByRange(Random random, int min, int max) {
		if (random == null) {
			random = new Random();
		}
		int s = random.nextInt(max) % (max - min + 1) + min;
		return s;
	}

	public static Integer getRandomByRange(int min, int max) {
		Random random = new Random();
		return getRandomByRange(random, min, max);
	}

	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("\\-", "");
	}

	public static boolean isMobile(String mobile) {
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(17[0,6-8])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobile);
		return m.matches();
	}

	public static String replaceJsonSpecialCharacter(String json) {
		if (StringUtils.isEmpty(json)) {
			return json;
		}
		StringBuffer sb = new StringBuffer();
		int length = json.length();
		for (int i = 0; i < length; i++) {
			char c = json.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 计算from到to的两个时间间隔
	 * 
	 * @param from
	 * @param to
	 * @return
	 */
	public static String getInterval(Date from, Date to) {
		if (from == null || to == null) {
			return "";
		}
		Date d1 = from;
		Date d2 = to;
		if (from.compareTo(to) > 0) {
			d1 = to;
			d2 = from;
		}
		String interval = null;
		long between = (d2.getTime() - d1.getTime()) / (1000L);
		if (between < 600) {
			interval = "刚刚";
		} else if (between >= 600 && between < 3600) {
			interval = between / 60 + "分种";
		} else if (between > 3600 && between < 86400) {
			interval = between / 3600 + "小时";
		} else if (between >= 86400) {
			interval = between / 86400 + "天";
		}
		return interval;
	}

	public static String getCellValue(Cell cell) {
		if (cell == null) {
			return "";
		}
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC:
			return doubleToString(cell.getNumericCellValue());
		case Cell.CELL_TYPE_STRING:
			return cell.getStringCellValue();
		case Cell.CELL_TYPE_BLANK:
			return "";
		case Cell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();
		default:
			return cell.getStringCellValue();
		}
	}

	public static String doubleToString(double d) {
		String i = DecimalFormat.getInstance().format(d);
		String result = i.replaceAll(",", "");
		return result;
	}

	// ----------------------------图片添加、交换、删除的私有方法----------------------------

	public static String addImg(String key, String str) {
		if (StringUtils.isEmpty(key)) {
			return str;
		}
		if (str == null) {
			str = key + ";";
		} else {
			str = str + key + ";";
		}
		return str;
	}

	public static List<String> subImg(String imgs) {
		List<String> list = new ArrayList<String>();
		if (StringUtils.isNotBlank(imgs)) {
			String[] imgArray = imgs.split("\\;");
			for (String img : imgArray) {
				list.add(img);
			}
		}
		return list;
	}

	public static String swapImg(String currentId, String previousId, String str) {
		Integer currentIndex = null;
		Integer previousIndex = null;
		String[] split = str.split("\\;");
		int length = split.length;
		if (length > 0) {
			for (int i = 0; i < length; i++) {
				if (split[i].equals(currentId)) {
					currentIndex = i;
				}
				if (split[i].equals(previousId)) {
					previousIndex = i;
				}
			}
		}
		if (currentIndex == null || previousIndex == null) {
			throw new ZhuziException(ErrorCode.Paramter_Error);
		}
		split[currentIndex] = previousId;
		split[previousIndex] = currentId;
		StringBuffer sb = new StringBuffer();
		for (String s : split) {
			if (StringUtils.isNotBlank(s)) {
				sb.append(s + ";");
			}
		}
		return sb.toString();
	}

	public static String delImg(String key, String str) {
		if (StringUtils.isEmpty(key)) {
			return str;
		}
		String[] split = str.split("\\;");
		StringBuffer sb = new StringBuffer("");
		for (String s : split) {
			if (s.equals(key)) {
				continue;
			} else {
				if (StringUtils.isNotEmpty(s)) {
					sb.append(s + ";");
				}
			}
		}
		return sb.toString();
	}

	// ----------------------------构建Spring Data Jpa封装的分页，排序对象----------------------------
	/**
	 * 生成PageRequest对象。默认按sortNo正序排序
	 * 
	 * @param pageNumber 第几页开始。例如第一页，pageNumber=0
	 * @param pageSize 每页显示数量
	 * @param sort 排序字段
	 * @param order 正序还是倒序ASC或DESC
	 * @return
	 */
	public static PageRequest buildBySortNoAscPageRequest(int pageNumber, int pageSize, String sort, String order) {
		Sort s = null;
		if (StringUtils.isBlank(sort) || StringUtils.isBlank(order)) {
			s = new Sort(Direction.ASC, "sortNo");
		} else {
			Direction direction = DynamicSpecifications.getDirection(order);
			s = new Sort(direction, sort);
		}
		return new PageRequest(pageNumber, pageSize, s);
	}

	/**
	 * 生成PageRequest对象。默认按id正序排序
	 * 
	 * @param pageNumber 第几页开始。例如第一页，pageNumber=0
	 * @param pageSize 每页显示数量
	 * @param sort 排序字段
	 * @param order 正序还是倒序ASC或DESC
	 * @return
	 */
	public static PageRequest buildByIdAscPageRequest(int pageNumber, int pageSize, String sort, String order) {
		Sort s = null;
		if (StringUtils.isBlank(sort) || StringUtils.isBlank(order)) {
			s = new Sort(Direction.ASC, "id");
		} else {
			Direction direction = DynamicSpecifications.getDirection(order);
			s = new Sort(direction, sort);
		}
		return new PageRequest(pageNumber, pageSize, s);
	}

	/**
	 * 生成排序对象，默认按id正序排序
	 * 
	 * @param sort
	 * @param order
	 * @return
	 */
	public static Sort buildByIdAsc(String sort, String order) {
		Sort s = null;
		if (StringUtils.isBlank(sort) || StringUtils.isBlank(order)) {
			s = new Sort(Direction.ASC, "id");
		} else {
			Direction direction = DynamicSpecifications.getDirection(order);
			s = new Sort(direction, sort);
		}
		return s;
	}

	/**
	 * 生成排序对象，默认按id倒序排序
	 * 
	 * @param sort
	 * @param order
	 * @return
	 */
	public static Sort buildByIdDesc(String sort, String order) {
		Sort s = null;
		if (StringUtils.isBlank(sort) || StringUtils.isBlank(order)) {
			s = new Sort(Direction.DESC, "id");
		} else {
			Direction direction = DynamicSpecifications.getDirection(order);
			s = new Sort(direction, sort);
		}
		return s;
	}

	/**
	 * 生成封装的Hibernate的CriteriaQuery
	 * 
	 * @param searchParams 查询条件Map对象
	 * @param clazz 查询的实体对象
	 * @return
	 */
	public static <T> Specification<T> buildSpecification(Map<String, Object> searchParams, final Class<T> clazz) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(), clazz);
		return spec;
	}
	
	
	 /**
     * <li>功能描述：时间相减得到天数
     * @param beginDateStr
     * @param endDateStr
     * @return
     * long 
     * @author Administrator
     */
    public static long getDaySub(String beginDateStr,String endDateStr)
    {
        long day=0;
        java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");    
        java.util.Date beginDate;
        java.util.Date endDate;
        try
        {
            beginDate = format.parse(beginDateStr);
            endDate= format.parse(endDateStr);    
            day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);    
            //System.out.println("相隔的天数="+day);   
        } catch (ParseException e)
        {
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }   
        return day;
    }
}
